package com.blb.ioc.myspring;

import com.blb.ioc.Computer;
import com.blb.ioc.MyComputer;

import java.lang.reflect.Field;

/**
 * 工厂模式,用于创建电脑对象
 */
public class ComputerFactory {
    public Object getBean(Class clazz) throws InstantiationException, IllegalAccessException {
        //创建类的对象
        Object obj = clazz.newInstance();
        //获取类的所有属性
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            Myvalue myvalue = field.getDeclaredAnnotation(Myvalue.class);
            //读取注解上的值
            if (myvalue!=null){
                String value = myvalue.value();
                //给属性赋值
                field.setAccessible(true);
                field.set(obj,value);
            }
            MyComponent myComponent = field.getDeclaredAnnotation(MyComponent.class);
            if (myComponent!=null){
                Class type = myComponent.type();
                Object myComponentObj = type.newInstance();
                field.setAccessible(true);
                field.set(obj,myComponentObj);
            }
        }
        return obj;
        //获取属性上配置的注解
        //读取注解中的值
    }

    public static void main(String[] args){
        ComputerFactory computerFactory = new ComputerFactory();
        try {
            MyComputer myComputer = (MyComputer) computerFactory.getBean(MyComputer.class);
            myComputer.start();
        } catch (Exception e) {
           e.printStackTrace();
        }

    }

}
